<template>
  <el-dialog v-model="props.statisticsData.showStatisticsDialog" width="850px" custom-class="statistics-dialog" @opened="openStatisticsDialog" @closed="closeStatisticsDialog">
    <div class="statistics-dialog-header">
      <div class="statistics-dialog-header-info">
        <div class="statistics-dialog-header-img">
        </div>
        <div class="statistics-dialog-header-text">
          <span class="statistics-dialog-header-text-title">{{ props.statisticsData.shortData.name }}</span><br>
          <span class="statistics-dialog-header-text-link">{{ props.statisticsData.shortData.short_url }}</span>
        </div>
      </div>
      <div class="statistics-dialog-header-opreate">
        <el-tabs v-model="queryStatistics.activeStatistics" @tab-click="changeTab">
          <el-tab-pane label="数据图表" name="dataChart"></el-tab-pane>
          <el-tab-pane label="访问记录" name="accessRecord"></el-tab-pane>
        </el-tabs>
        <div class="share-date-export">
          <span @click="exportsImg">
            导出图片<img :src="dataStatisticsImgRootSrc+'download_white_logo.png'" alt="download_white_logo">
          </span>
          <span>
            生成分享链接<img :src="dataStatisticsImgRootSrc+'share_white_logo.png'" alt="share_white_logo">
          </span>
        </div>
        <div class="share-data-date">
          <el-date-picker v-model="props.statisticsData.formData.time" type="daterange" size="small" :disabled-date="queryStatistics.disabledDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :clearable="false" :shortcuts="queryStatistics.shortcuts" @change="openStatisticsDialog">
          </el-date-picker>
        </div>
      </div>
    </div>
    <div v-loading="queryStatistics.querying">
      <div class="empty-box" v-show="!queryStatistics.showCharts">
        <img src="/img/404-images/empty.png" alt="empty.png"><br>
        <span>所选日期暂无访问记录</span>
      </div>
      <div class="charts-content" v-show="queryStatistics.showCharts">
        <div v-show="queryStatistics.activeStatistics == 'dataChart'">
          <div class="content-card">
            <el-card v-for="item in queryStatistics.accessType" :key="item">
              <div class="content-card-left">
                <div class="left-logo">
                  <img :src="dataStatisticsImgRootSrc+item.img+'.png'" :alt="item.img">
                </div>
                <div class="content-card-left-text">
                  <span class="content-card-data">{{ item.data }}</span>
                  <span class="content-card-title">{{ item.title }}</span>
                </div>
              </div>
            </el-card>
          </div>
          <DataCurveChart :time="props.statisticsData.formData.time" ref="dataCurveChartRef" />
          <MapPlugin ref="mapPluginRef" />
          <el-row>
            <el-col :span="24">
              <OperatePieChart ref="operatePieChartRef" />
            </el-col>
          </el-row>
          <AccessSource :accessData="{accessIp:queryStatistics.accessIp,accessSource:queryStatistics.accessSource}" ref="accessSourceRef" />
        </div>
        <div v-show="queryStatistics.activeStatistics == 'accessRecord'" v-loading="queryStatistics.tableLoading">
          <el-table :data="queryStatistics.accessTableData" height="550px">
            <el-table-column prop="create_time" label="日期" width="150">
            </el-table-column>
            <el-table-column prop="ip" label="访问IP">
            </el-table-column>
            <el-table-column prop="city" label="访问地区">
              <template #default="{ row }">
                <span style="font-size: 12px;">{{[row.country,row.province,row.city].filter(item=>item != '').join('-')}}</span>
              </template>
            </el-table-column>
            <el-table-column label="访问设备" width="120px">
              <template #default="{ row }">
                <div style="display: flex;justify-content: space-between;">
                  <img :src="imgRootSrc+ row.platform +'.svg'" alt="ios_icon" :title="`系统：${row.platform}`">
                  <img :src="imgRootSrc+ row.browser +'.svg'" alt="wechat_icon" :title="`浏览器：${row.browser}`">
                  <!--区分电脑还是手机-->
                  <img v-if="row.is_mobile == 0" :src="imgRootSrc+'电脑.svg'" alt="computer_icon" title="设备：电脑">
                  <img v-else :src="imgRootSrc+'手机.svg'" alt="computer_icon" title="设备：手机">
                  <!--区分数据还是wifi-->
                  <img v-if="row.is_wifi == 1" :src="imgRootSrc+'Wi-Fi.svg'" alt="wifi_icon" title="网络：WIFI">
                  <img v-else :src="imgRootSrc+'数据.svg'" alt="wifi_icon" title="网络：数据">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="referer" label="访问来源" show-tooltip-when-overflow>
            </el-table-column>
            <el-table-column prop="is_new" label="访客类型" width="70px">
              <template #default="{ row }">
                <span>{{row.is_new ? '新访客' :'老访客'}}</span>
              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-pagination
              background
              layout="total, prev, pager, next"
              :total="paginationData.total"
              :current-page="paginationData.page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="paginationData.per_page"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { reactive, getCurrentInstance, nextTick } from 'vue'
import { shortStatistics, liveCodeStatistics } from '@/axios/userRequest'
import MapPlugin from './mapPlugin'
import OperatePieChart from './operatePieChart'
import DataCurveChart from './dataCurveChart'
import AccessSource from './accessSource'
import { get_data_statistics_by_id } from '@/axios/userRequest'
import { DomToImg } from '@/utils/utils'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const imgRootSrc = '/img/data-statistics-images/icon/'
const dataStatisticsImgRootSrc = '/img/data-statistics-images/'

const props = defineProps({
  statisticsData:Object
})

props.statisticsData.formData.time = [
  proxy.$filter('YYYY-mm-dd',new Date(new Date(new Date().toDateString()).getTime() - 3600 * 1000 * 24 * 7)),
  proxy.$filter('YYYY-mm-dd',new Date(new Date(new Date().toDateString()).getTime()))
]

const paginationData = reactive({
  total:0,
  page:1,
  per_page:10,
})
// 数据统计弹窗数据
const queryStatistics = reactive({
  activeStatistics:'dataChart',
  tableLoading: false,
  accessType: {},// 访问类型
  querying:true, // 查询中
  showCharts:false, // 显示图表
  accessTableData: [], // 访问记录表格数据
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        return [start, end]
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        return [start, end]
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        return [start, end]
      },
    },
  ],
  disabledDate:(time)=>{
    return time.getTime() > Date.now()
  }
})
let shortLinkVisit = {// 短链访问数据
  'today_visit_num': { title: '新访客人数', data: 0, img: 'eye_logo' },
  'total_num': { title: '累计访问人数', data: 0, img: 'time_logo' },
  'is_wifi_num': { title: 'Wifi访问人数', data: 0, img: 'wifi_logo' },
  'is_not_wifi': { title: '移动数据访问人数', data: 0, img: 'data_logo' },
}
let liveCodeVisit = {// 活码访问数据
  'code_today_scan_num': { title: '新扫码次数', data: 0, img: 'scan_code_today_logo' },
  'code_today_scan_person': { title: '新扫码人数', data: 0, img: 'number_of_scanners_today_logo' },
  'code_total_num': { title: '累计扫码次数', data: 0, img: 'cumulative_scan_times_logo' },
  'code_total_peo_num': { title: '累计扫码人数', data: 0, img: 'total_number_of_scanned_codes_logo' },
}
// 打开数据统计弹窗
const openStatisticsDialog = async (time=[])=>{
  queryStatistics.querying = true
  let form = {
    ...props.statisticsData.formData
  }
  time.length === 2 ? form.time = time.map(item => proxy.$filter('YYYY-mm-dd',item)) : ''
  getList()
  let result = props.statisticsData.type === 1 ? shortStatistics : liveCodeStatistics
  queryStatistics.accessType = props.statisticsData.type === 1 ? shortLinkVisit : liveCodeVisit
  const res = await result(form)
  if(res.code === 0){
    if(res.data.total_num.count !== 0){
      for (let key in res.data){
        Object.keys(queryStatistics.accessType).includes(key) ? queryStatistics.accessType[key].data = res.data[key].count : ''
      }
      proxy.$refs.dataCurveChartRef.chartOption(res.data.visit_data,props.statisticsData.shortData.name)
      proxy.$refs.mapPluginRef.chartOption(res.data.province_data,res.data.country_data,res.data.total_num.count)
      proxy.$refs.operatePieChartRef.chartOption(res.data.platform_data,res.data.browser_data)
      proxy.$refs.accessSourceRef.setData(res.data.ip_data,res.data.referer_data)
      queryStatistics.showCharts = true
      await nextTick(()=>resizeChart())
    }else{
      queryStatistics.showCharts = false
    }
  }else{
    proxy.$message.error(res.msg)
  }
  queryStatistics.querying = false
}
// 重置图表
const resizeChart = ()=>{
  proxy.$refs.dataCurveChartRef.chartResize()
  proxy.$refs.operatePieChartRef.chartResize()
  proxy.$refs.mapPluginRef.chartResize()
}

const changeTab = () => nextTick(()=>resizeChart())

const closeStatisticsDialog = ()=>{
  emit('update:showStatisticsDialog',false)
  queryStatistics.showCharts = false
}

const getList = () => {
  queryStatistics.tableLoading = true
  get_data_statistics_by_id({
    type:props.statisticsData.type,
    group:props.statisticsData.formData.type,
    time:props.statisticsData.formData.time,
    id:props.statisticsData.formData.code_id ? props.statisticsData.formData.code_id : props.statisticsData.formData.short_id,
    ...paginationData,
  }).then(res=>{
    if(res.code == 0){
      queryStatistics.accessTableData = res.data.data.data
      paginationData.total = res.data.data.total
    }
    queryStatistics.tableLoading = false
  })
}

const handleCurrentChange = (val) => {
  paginationData.page = val
  getList()
}

const handleSizeChange = (val)=>{
  paginationData.per_page = val
  getList()
}

const exportsImg = () => {
  let title = document.querySelector('.statistics-dialog-header-text-title').innerText
  DomToImg(document.querySelector('.el-dialog__body'),`数据统计-${title}-${+new Date()}`).then(()=>{
    proxy.$message.success('保存成功')
  }).catch(()=>{
    proxy.$message.error('导出失败')
  })
}
</script>

<style lang="less" scoped>
.el-table{
  &:deep(.cell){
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
}
.el-table::before{
  display: none;
}
</style>

<style lang="less">
.statistics-dialog{
  margin-top: 40px !important;
  max-width: unset;
  .el-dialog__header{
    height: 25px;
    background-color: @primary;
  }
  .el-dialog__body{
    padding: 0;
    max-height: unset;
    .statistics-dialog-header{
      background-color: @primary;
      //height: 115px;
      padding: 0 32px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .statistics-dialog-header-text-link{
        font-size: 14px;
        line-height: 22px;
        color: #fff;
      }
      .statistics-dialog-header-info{
        display: flex;
        .statistics-dialog-header-img{
          //padding-right: 24px;
        }
        .statistics-dialog-header-text{
          color: #FFFFFF;
          .statistics-dialog-header-text-title{
            font-size: 24px;
            line-height: 37px;
          }
        }
      }
      .statistics-dialog-header-opreate{
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        //padding-left: 24px;
        .share-date-export {
          color: #FFFFFF;
          padding-bottom: 7px;
          margin-left: 150px;
          span{
            display: inline-flex;
            align-items: center;
            margin-right: 15px;
            font-size: 12px;
            cursor: pointer;
            img{
              margin-left: 8px;
            }
          }
        }
        .share-data-date {
          padding-bottom: 5px;
          .el-date-editor {
            width: 240px;
            .el-range__close-icon{
              display: none;
            }
          }
        }
      }
    }
    .empty-box{
      text-align: center;
      padding: 100px 0;
      img{
        margin-bottom: 30px;
      }
      span{
        color: @secondary;
      }
    }

    .el-tabs{
      margin-top: 30px;
      .el-tabs__header{
        margin: 0 0px;
        .el-tabs__nav-wrap{
          .el-tabs__nav-scroll{
            .el-tabs__nav{
              .el-tabs__active-bar{
                width: 60px !important;
                height: 5px;
                background-color:#fff;
              }
              .el-tabs__item{
                font-size: 14px;
                color: #f8f8f8 !important;
              }
            }
          }
        }
        .el-tabs__nav-wrap::after{
          height: 0 !important;
        }

      }
      .el-tabs__content{
        //padding-top: 30px;
      }
    }
    .cell{
      font-size: 12px;
      img{
        width: 16px;
      }
    }
    .charts-content{
      padding: 20px;
      .content-card{
        display: flex;
        margin: 0 20px;
        .el-card{
          .el-card__body{
            padding-left: 0;
          }
          &:nth-last-of-type(1){
            .el-card__body{
              padding-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>
